<?php
/**
 * Created by PhpStorm.
 * User: hoter.zhang
 * Date: 2016/9/5
 * Time: 15:49
 */

namespace app\core\behaviors;


use app\models\AdminLog;
use Yii;
use yii\base\Behavior;
use yii\base\Event;
use yii\db\ActiveRecord;
use yii\helpers\Url;
use yii\web\Application;

class AdminLogBehavior extends Behavior
{

    public function events(){
        return [
            Application::EVENT_BEFORE_REQUEST => 'handle',
        ];
    }

    public function handle(){
//        Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, [$this, 'log']);
        Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_UPDATE, [$this, 'log']);
//        Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_DELETE, [$this, 'log']);
    }

    public function log($event){
        if(!empty($event->changedAttributes)) {
            $desc = '';
            foreach($event->changedAttributes as $name => $value) {
                $desc .= $name . ' : ' . $value . '=>' . $event->sender->getAttribute($name) . ',';
            }
            $desc = substr($desc, 0, -1);
            $userName = isset(Yii::$app->user->identity->username) ?: '未登录';
            $tableName = $event->sender->tableSchema->name;
            $description = "%s修改了表%s %s:%s的%s";
            $description = sprintf($description, $userName, $tableName, $event->sender->primaryKey()[0], $event->sender->getPrimaryKey(), $desc);
            $route = Url::to();
            $userId = isset(Yii::$app->user->id) ?: 0;
            //$ip = ip2long(Yii::$app->request->userIP);
            $ip = Yii::$app->request->userIP;
            $data = [
                'route' => $route,
                'description' => $description,
                'created_at' => time(),
                'updated_at' => time(),
                'user_id' => $userId,
                'ip' => $ip
            ];
            $model = new AdminLog();
            $model->setAttributes($data);
            if (!$model->save() ) {
                print_r($model->getFirstErrors());die;
            }
        }
    }
}